package com.springboot.service;

import com.springboot.constant.CommonConstant;
import com.springboot.domain.BtComment;
import com.springboot.domain.BtDemand;
import com.springboot.domain.BtUser;
import com.springboot.dto.AddCommentDTO;
import com.springboot.repository.CommentRepository;
import com.springboot.repository.DemandRepository;
import com.springboot.repository.TaskRepository;
import com.springboot.repository.UserRepository;
import com.springboot.tools.UUIDTool;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;

@Service
@Transactional
public class CommentService {
    private DemandRepository demandRepository;
    private CommentRepository commentRepository;
    private UserRepository userRepository;
    private TaskRepository taskRepository;

    public CommentService(DemandRepository demandRepository, CommentRepository commentRepository, UserRepository userRepository, TaskRepository taskRepository) {
        this.demandRepository = demandRepository;
        this.commentRepository = commentRepository;
        this.userRepository = userRepository;
        this.taskRepository = taskRepository;
    }

    public void addComment(AddCommentDTO addCommentDTO, String userId) {
        BtUser user = userRepository.findByUserId(userId);
        BtDemand demand = demandRepository.findOne(addCommentDTO.getDemandId());
        String receiver;
        //查找评论接收方
        if (user.getUserType().equals(CommonConstant.USER_BANK)){ //评论方为银行
            receiver = taskRepository.findOne(demand.getTaskId()).getReceiver();
        }else {                                                   //评论方为个人或企业
            receiver = demand.getBankId();
        }
        //获取当前项目的最高楼层
        Integer maxFloor = commentRepository.findMaxFloorByDemand(addCommentDTO.getDemandId());
        if (maxFloor == null){
            maxFloor = 1;
        }else {
            maxFloor += 1;
        }
        BtComment comment = new BtComment();
        comment.setId(UUIDTool.getUuid());
        comment.setCreateTime(new Date());
        comment.setAnnouncer(userId);
        comment.setDemandId(addCommentDTO.getDemandId());
        comment.setReceiver(receiver);
        comment.setLevel(addCommentDTO.getLevel());
        comment.setComment(addCommentDTO.getComment());
        comment.setFloor(maxFloor);
        commentRepository.save(comment);

    }
}
